var debugMode = false;

/**
 * 上传图片并返回检测结果
 */
function defectApi(files=[], params={}, url="/api/predict") {
    if (!files || !files.length) {
        return Promise.reject(new Error("请选择一张图片!"));
    }
    if (files.length > 1) {
        return Promise.reject(new Error("目前只支持单张图片!"));
    }

    const formData = new FormData();

    for (let item of files) {
        formData.append("file", item);
    }

    if (params) {
        for (let key in params) {
            formData.append(key, params[key]);
        } 
    }

    return fetch(url, {
        method: "POST",
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("网络响应异常");
        }
        return response.json();
    })
}


function processResult(data, imageUrl, canvasElement) {
    // 获取上下文
    const canvas = canvasElement.getContext("2d");

    // 显示用户上传的图片
    const img = new Image();
    img.src = imageUrl;
    img.onload = () => {
        // 设置 canvas 元素的 width 和 height 属性
        canvasElement.width = img.width;
        canvasElement.height = img.height;

        // 清空 canvas
        canvas.clearRect(0, 0, canvasElement.width, canvasElement.height);

        // 绘制图像
        canvas.drawImage(img, 0, 0);

        // 绘制检测框
        canvas.strokeStyle = "red";
        canvas.lineWidth = 2;
        canvas.font = "14px Arial";
        canvas.fillStyle = "red";

        data.defect_boxes.forEach(box => {
            // const ratio = img.width / data.image.targetWidth;
            const horizontalRatio = data.image.horizontalRatio;
            const verticalRatio = data.image.verticalRatio;
            // const ratio = 1;

            const [ x, y, width, height ] = [
                Math.round(box.x1 * horizontalRatio),
                Math.round(box.y1 * verticalRatio),

                Math.round((box.x2 - box.x1) * horizontalRatio),
                Math.round((box.y2 - box.y1) * verticalRatio),
            ];

            if (debugMode) console.debug("strokeRect: ", x, y, width, height);
            canvas.strokeRect(x, y, width, height);
            // canvas.fillText(box.confidence.toFixed(2), box.x1, box.y1 - 5);
        });

        // ✅ 关键：清除事件监听器和引用
        img.onload = null;
        img.onerror = null;
    };

    img.onerror = () => {
        // resultDiv.textContent = "无法加载图片";
        console.error("图片加载失败");
        alert('"无法加载图片"')

        // ✅ 关键：清除事件监听器和引用
        img.onload = null;
        img.onerror = null;
    };
}
